/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.rabbitmq.consumer;

import com.geekc.rabbitmq.constant.RabbitMQConst;
import com.geekc.rabbitmq.domain.Message;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 业务消费者
 * @author Carnegie Lee
 */
@Component
public class Consumer {

    /**
     * 接收消息
     */
    @RabbitHandler
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "queue.demo", durable = "true", arguments = {
                            @Argument(name = "x-dead-letter-exchange", value = RabbitMQConst.RABBITMQ_DLX_EXCHANGE_NAME),
                            @Argument(name = "x-dead-letter-routing-key", value = RabbitMQConst.RABBITMQ_DLX_ROUTING_KEY)
                    }),
                    exchange = @Exchange(value = RabbitMQConst.RABBITMQ_EXCHANGE_NAME, durable = "true", type = "topic", arguments = {
                            @Argument(name = "alternate-exchange", value = RabbitMQConst.RABBITMQ_BAK_EXCHANGE_NAME)
                    }),
                    key = "#"
            )
    )
    public void messageHandler(@Payload Message message, Channel channel, @Headers Map<String, Object> headers) {
        System.out.println("接收到消息[id:" + message.getMessageId() + ",body:" + message.getMessageBody() + "]");
        //TODO
        /** 签收消息 */
        /*Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        /** 拒绝签收 */
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
             channel.basicReject(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
